package com.han.nettytestdemo.connector.communication;

import android.util.Log;

import com.han.nettytestdemo.connector.LogUtil;
import com.han.nettytestdemo.connector.netty.NettyHcUtil;
import com.han.nettytestdemo.connector.netty.NettyUtil;
import com.han.nettytestdemo.connector.netty.intf.ConnectClientCallback;
import com.han.nettytestdemo.connector.netty.intf.ConnectHCClientCallback;
import com.han.nettytestdemo.connector.netty.intf.MessageClientCallback;
import com.han.nettytestdemo.connector.netty.intf.MessageHcClientCallback;

import io.netty.util.internal.StringUtil;


/**
 * Created by zoubin on 2017/7/18.
 */

public class SocketClientImpl implements SocketHostSerialInterface,
        ConnectClientCallback, MessageClientCallback,
        ConnectHCClientCallback, MessageHcClientCallback {

    public static final String TAG = SocketClientImpl.class.getSimpleName();
    private StringBuilder sd_plc = new StringBuilder();
    private StringBuilder sd_hc = new StringBuilder();

    private int portPlc = 26;
    private ProtocolType protocolType = ProtocolType.PLC;
    private int outTime = 2000;

    private boolean isPlcNetty = false;//NettyPlc是否连接
    private boolean isHcNetty = false;//NettyHc是否连接
    private int i = 0;

    public SocketClientImpl(String ip) {
        NettyUtil.getInstance().nettyConnect(ip, portPlc, this);
//        NettyHcUtil.getInstance().nettyConnect(ip, portHc, this);
    }

    @Override
    public void runOrder(Order order) {
        boolean isOk = false;
        try {
            protocolType = order.protocolType;
            try {
                String cmd[][] = order.getCmd();
                for (String a[] : cmd) {
                    switch (protocolType) {
                        case PLC:
                            if (isPlcNetty) {
                                sendPlcCmd(a);
                            } else {
                                order.getProductCallback().onDataReceived(ProductCallback.Err, "没有连接上");
                            }
                            break;
                        case MODBUS:
                            if (isHcNetty) {
                                sendModBusCmd(a);
                            } else {
                                order.getProductCallback().onDataReceived(ProductCallback.Err, "没有连接上");
                            }
                            break;
                    }
                }
                long startTime = System.currentTimeMillis();

                while (!isOk) {
                    if (readDataStr().length() > 0) {
                        StringBuilder sdcp = readDataStr();
                        order.getProductCallback().onDataReceived(ProductCallback.Sur, sdcp.toString());
                        clearCache();
                        isOk = true;
                    } else {
                        if (((System.currentTimeMillis() - startTime) > outTime)) {
                            order.getProductCallback().onDataReceived(ProductCallback.Err, "获取" + protocolType.name() + "反馈超时");
                            clearCache();
                            i++;
                            if (i > 3) {
                                i = 0;
                            }
                            isOk = true;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, e.getMessage());
                order.getProductCallback().onDataReceived(ProductCallback.Err, "网络异常！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            order.getProductCallback().onDataReceived(ProductCallback.Err, "网络异常");
        }
    }


    @Override
    public boolean isConnected() {
        return false;
    }

    @Override
    public void sendPlcCmd(String[] cmd) {
        StringBuilder sb = new StringBuilder();
        for (String s1 : cmd) {
            sb.append(s1);
        }
        try {
            NettyUtil.getInstance().setNettyPost(sb.toString());
//            Log.d(TAG, "PLC命令发送成功 : " + DateUtil.getStrTime() + "Send communication Succese！" + sb);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "PLC命令发送错误: " + "bulkOut传输-1");
        }
    }

    @Override
    public void sendModBusCmd(String[] cmd) {
        StringBuilder sb = new StringBuilder();
        for (String s1 : cmd) {
            sb.append(s1);
        }
        try {
            NettyHcUtil.getInstance().setNettyPost(sb.toString());
            Log.d(TAG, "温湿度命令发送成功 : " + "Send communication Succese！");
        } catch (Exception e) {
            Log.d(TAG, "温湿度命令发送错误: " + "err" + Log.getStackTraceString(e));
        }
    }

    @Override
    public StringBuilder readDataStr() {
        switch (protocolType) {
            case PLC:
                return sd_plc;
            case MODBUS:
                return sd_hc;
        }
        return null;
    }

    @Override
    public void clearCache() {
        switch (protocolType) {
            case PLC:
                sd_plc.setLength(0);
                break;
            case MODBUS:
                sd_hc.setLength(0);
                break;
        }
    }

    @Override
    public void onConnect(int code, String message) {
        LogUtil.e(TAG, "PLC:" + message);
        if (code == 0) {
            isPlcNetty = true;
            NettyUtil.getInstance().setMessageClientCallback(this);
        } else if (code == 1) {
            isPlcNetty = false;
        }
    }

    @Override
    public void messageClientCallback(String message) {
        try {
            String str = message;
//            LogUtils.e(TAG, "NETTY返回数据PLC:" + message);
            if (str.length() > 0) {
                sd_plc.setLength(0);
                sd_plc.append(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onHcConnect(int code, String message) {
        LogUtil.e(TAG, "HC:" + message);
        if (code == 0) {
            isHcNetty = true;
            NettyHcUtil.getInstance().setMessageClientCallback(this);
        } else if (code == 1) {
            isHcNetty = false;
        }
    }

    @Override
    public void onHcClientCallback(String message) {
        try {
            String str = message;
//            if (!StringUtil.isEmpty(message) && message.length() > 4) {
//                if (message.startsWith("0103")) {
//                    str = message;
//                }
//            }
//            LogUtils.e(TAG, "NETTY返回数据HC:" + message);
            if (str.length() > 0) {
                sd_hc.setLength(0);
                sd_hc.append(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
